package com.borya.filter;


import java.util.Iterator;
import java.util.Set;
import java.util.function.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.borya.framework.annotation.Filter;
import com.borya.framework.core.ServerFilter;
import com.borya.framework.core.ServerRequest;
import com.borya.framework.core.ServerResponse;
import com.borya.statuscode.StatusCode;
import com.borya.util.Base64;
import com.borya.util.StringUtil;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import io.netty.util.CharsetUtil;

@Filter
public class WebServerFilter implements ServerFilter {

    private Logger log = Logger.getLogger(getClass());

    //	private static final String ip = SystemConfig.getInstance().getProperty("web.ip");
    @Override
    public boolean doFilter(ServerRequest request, ServerResponse response) {
        final String host = request.ip();
        final String url = request.path();
        final String text = request.text();

        Predicate<String> pre = str -> !str.contains("/w/");
        boolean test = pre.test(url);
        if (test) {
            return false;
        }

        if (StringUtils.isBlank(text)) {
            log.warn("[" + host + "] Server recv msg is empty,url=" + url);
            return true;
        }
        String get_sessionId = getSessionId(request.headers().get(HttpHeaderNames.COOKIE));

        try {
            if (url.contains("/w/upload/")) {
                log.debug("upload text");
                return false;
            }
            //校验token信息
            String jso_str = Base64.decodeString(text);
            JSONObject json = JSONObject.parseObject(jso_str);
            if (json == null) {
                log.warn("[" + host + "] Parse json error,url=" + url);
                response.content().writeBytes(StatusCode.PARAM_ERROR.toJSON("JSON格式错误").getBytes(CharsetUtil.UTF_8));
                return true;
            }


            String sessionId = StringUtil.randomNumberString(12);
            json.put("set_sessionId", sessionId);
            if (get_sessionId != null) {
                json.put("get_sessionId", get_sessionId);
            }
            response.headers().add(HttpHeaderNames.SET_COOKIE, "sessionId=" + sessionId);
            request.setAttribute("json", json);
            return false;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.content().writeBytes(StatusCode.PARAM_ERROR.toJSON("参数错误").getBytes(CharsetUtil.UTF_8));
            return true;
        }
    }

    private String getSessionId(String cookiesStr) {
        //String cookieString = request.headers().get(HttpHeaderNames.COOKIE);
        if (cookiesStr == null) {
            return null;
        }

        Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookiesStr);
        if (!cookies.isEmpty()) {
            Iterator<Cookie> it = cookies.iterator();
            while (it.hasNext()) {
                Cookie a = it.next();
                if ("sessionId".equals(a.name())) {
                    String get_sessionId = a.value();
                    return get_sessionId;
                }
            }
        }

        return null;
    }
}